package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Auther：DONG on 2021/11/7
 **/
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fastdfs.url}")
    private String fastServerUrl;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        String fileurl;
        try {
            fileurl = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_FAIL);
        }
        WmMaterial wmMaterial = new WmMaterial();
        WmUser wmUser = WmThreadLocalUtils.getUser();
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setUrl(fileurl);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        boolean saveResult = this.save(wmMaterial);
        if (!saveResult) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SAVE_FATL);

        }
        wmMaterial.setUrl(fastServerUrl + fileurl);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.参数校验
        dto.checkParam();
        //2.根据isCollection进行查询
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.<WmMaterial>lambdaQuery();

        if (dto != null && dto.getIsCollection().shortValue() == 1) {
            //查询收藏的
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //3.根据当前登录用户进行查询
        WmUser wmUser = WmThreadLocalUtils.getUser();
        lambdaQueryWrapper.eq(WmMaterial::getUserId, wmUser.getId());
        //4.根据时间进行倒叙查询返回
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //5.调用api进行列表查询
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> pageResult = page(page, lambdaQueryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        //  给每个素材拼接url
        List<WmMaterial> wmMaterialList = pageResult.getRecords();
        List<WmMaterial> newWmMaterialList = wmMaterialList.stream().map(item -> {
            item.setUrl(fastServerUrl + item.getUrl());
            return item;
        }).collect(Collectors.toList());


        //6.返回ResponseResult
        pageResponseResult.setData(newWmMaterialList);

        return pageResponseResult;
    }

    @Override
    public ResponseResult delWmMaterial(Integer id) {
        //1.参数校验
        if (null == id) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.根据id查询数据
        WmMaterial wmMaterial = getById(id);
        if (null == wmMaterial) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查看图片是否被引用  如果引用  就不能进行删除
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id);
        Integer wmNewsMaterialCount = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);
        if (wmNewsMaterialCount > 0) {
            //说明被引用
            return ResponseResult.errorResult(500, "被引用的素材不能删除");
        }

        //4.执行删除
        boolean removeResult = removeById(id);
        if (!removeResult) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FILE);
        }
        //删除fastDFS上的图片
        String fileId = wmMaterial.getUrl().replace(fastServerUrl, "");
        try {
            fastDFSClient.delFile(fileId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FILE, "fastDFS上的文件删除失败");
        }
        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult collect(Integer id, Short isCollection) {
            //参数校验
        if (null==id){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        LambdaUpdateWrapper<WmMaterial> lambdaUpdateWrapper = Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, isCollection).eq(WmMaterial::getId, id);

        boolean updateResult = update(lambdaUpdateWrapper);
        if (!updateResult){
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_FILE);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
